package userManagementUtil;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import persistent.Db4oServletListener;

import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Predicate;

import LoginUtil.User;

/**
 * Servlet implementation class userManagementServlet
 */
public class userManagementServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public userManagementServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		ObjectContainer container = 
	        (ObjectContainer)request.getAttribute(Db4oServletListener.KEY_DB4O_SESSION);
		
		System.out.println("Parameter names:\n");
		Enumeration paramNames = request.getParameterNames();
		while(paramNames.hasMoreElements()) {
			System.out.println(paramNames.nextElement().toString());
		}
		
		final String selectedName = request.getParameter("userdrop");
		final String newFirstName = request.getParameter("firstnamebox");
		final String newLastName = request.getParameter("lastnamebox");
		final String newUsername = request.getParameter("usernamebox");
		final String newPassword = request.getParameter("passwordbox");
		final String suspended = request.getParameter("suspendedcheckbox");
		final String resetPassword = request.getParameter("resetpasswordcheckbox");
		final String deleteUser = request.getParameter("deletecheckbox");
		
		
		
		ObjectSet<User> rs = container.query(new Predicate<User>(){
					public boolean match(User user) {
						return user.getUsername().equals(selectedName);}});
		
		if(rs.size() > 0) {
			User user = rs.next();
			if(!newFirstName.equals("")) user.setFirstName(newFirstName);
			if(!newLastName.equals("")) user.setLastName(newLastName);
			if(!newUsername.equals("")) user.setUsername(newUsername);
			if(!newPassword.equals("")) user.setPassword(newPassword);
			if(suspended != null)
				user.setSuspended(true);
			else
				user.setSuspended(false);
			if(resetPassword != null) user.setPassword("");
			container.store(user);			

			if(deleteUser != null) {
				container.delete(user);
			}

			container.commit();
		}
		
		response.sendRedirect("userManagement.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		throw new ServletException("unimplemented");
	}

}
